#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

// compile: gcc main.c -lwsock32 && a
int main()
{
  WORD ws_version = MAKEWORD(2, 2);
  WSADATA wsaData;
  WSAStartup(ws_version, &wsaData);
  SOCKET serv_sock;
  serv_sock = socket(AF_INET, SOCK_STREAM, 0);
  SOCKADDR_IN serv_addr, clnt_addr;
  int clt_sz = sizeof(SOCKADDR);
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  serv_addr.sin_port = htons(8002);
  printf("running at 127.0.0.1:8002\n");
  bind(serv_sock, (SOCKADDR *)&serv_addr, sizeof(SOCKADDR));
  listen(serv_sock, 20);
  SOCKET clnt_sock;
//   char str[] = "HTTP/1.1 200 OK\r\ncontent-type: text/plain; charset=utf-8\r\nContent-length:11\r\n\r\n我owo world";
  char str404[] = "HTTP/1.1 404 Not Found\r\ncontent-type: text/html; charset=utf-8\r\nContent-length:13\r\n\r\n404 Not Found";
  while (1)
  {
    clnt_sock = accept(serv_sock, (SOCKADDR *)&clnt_addr, &clt_sz);
    char head[10240] = "HTTP/1.1 200 OK\r\ncontent-type:";
    char req_line[100];
    recv(clnt_sock, req_line, 100, 0);
    char file_name[30] = "/";

    int i;
    for (i = 5; req_line[i] != ' '; i++)
    {
      file_name[i - 5] = req_line[i];
    }
    printf("%s\n",file_name);
    if (strcmp(file_name, "favicon.ico") == 0)
    {
      send(clnt_sock, str404, sizeof(str404), 0);
      continue;
    }
    if (strcmp(file_name, "/") == 0)
    {
      strcpy(file_name, "index.html");
    }
    int len = strlen(file_name);
    if (file_name[len - 2] == 'm')
    {
      strcat(head, "text/html");
    }
    else if (file_name[len - 2] == 'j')
    {
      strcat(head, "application/javascript");
    }
    else if (file_name[len - 2] == 's')
    {
      strcat(head, "text/css");
    }
    else
    {
      strcat(head, "text/plain");
    }
    FILE *fp = NULL;
    char str[10240];
    int buff;
    i = 0;
    char length[30];
    fp = fopen(file_name, "r");
    if(fp==NULL)
    {
      send(clnt_sock, str404, sizeof(str404), 0);
      continue;
    }
    do
    {
      buff = fgetc((FILE *)fp);
      str[i] = buff;
      i++;
    } while (buff != EOF);
    fclose(fp);
    sprintf(length, "%d", i - 1);
    strcat(head, "\r\nContent-length:");
    strcat(head, length);
    strcat(head, "\r\n\r\n");
    strcat(head, str);
    send(clnt_sock, head, sizeof(head), 0);
  }
  closesocket(clnt_sock);
  closesocket(serv_sock);
  WSACleanup();
  return 0;
}